package jmine.tec.web.wicket.test;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.List;

import org.apache.wicket.Page;

/**
 * Classe que possui metodos utilitarios para testes de wicket
 * 
 * @author Rafael Volpato
 * @date Oct 4, 2011
 */
public final class WicketTestUtils {

    private static final String CLASS = ".class";

    /**
     * Construtor.
     */
    private WicketTestUtils() {
        super();
    }

    /**
     * Busca todas as paginas que extendem {@link Page} dentro dos pacotes informados
     * 
     * @param packages pacotes
     * @return Busca todas as paginas que extendem {@link Page} dentro dos pacotes informados
     */
    public static List<Class<Page>> findPagesClasses(String... packages) {
        if (packages == null || packages.length == 0) {
            return Collections.emptyList();
        }

        List<Class<Page>> classes = new ArrayList<Class<Page>>();
        for (String pack : packages) {
            try {
                classes.addAll(findPagesClasses(pack, Page.class));
            } catch (ClassNotFoundException e) {
                // ignore
            } catch (IOException e) {
                // ignore
            } catch (NoClassDefFoundError e) {
                // ignore
            }
        }
        return classes;
    }

    /**
     * Busca todas as paginas que extendem {@link Page} dentro dos pacotes informados
     * 
     * @param packages pacotes
     * @param basePageClass classe base que deve ser retornada
     * @param <T> Tipo da classe que deve ser retornada
     * @return Busca todas as paginas que extendem {@link Page} dentro dos pacotes informados
     */
    public static <T> List<Class<T>> findPagesClasses(String[] packages, Class<T> basePageClass) {
        if (packages == null || packages.length == 0) {
            return Collections.emptyList();
        }

        List<Class<T>> classes = new ArrayList<Class<T>>();
        for (String pack : packages) {
            try {
                classes.addAll(findPagesClasses(pack, basePageClass));
            } catch (ClassNotFoundException e) {
                // ignore
            } catch (IOException e) {
                // ignore
            } catch (NoClassDefFoundError e) {
                // ignore
            }
        }
        return classes;
    }

    /**
     * Scans all classes accessible from the context class loader which belong to the given package and subpackages.
     * 
     * @param packageName The base package
     * @param basePageClass classe base que deve ser retornada
     * @param <T> Tipo da classe que deve ser retornada
     * @return The classes
     * @throws ClassNotFoundException se acontecer algum erro
     * @throws IOException se acontecer algum erro
     */
    private static <T> List<Class<T>> findPagesClasses(String packageName, Class<T> basePageClass) throws ClassNotFoundException,
            IOException {
        ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
        String path = packageName.replace('.', '/');
        Enumeration<URL> resources = classLoader.getResources(path);
        List<File> dirs = new ArrayList<File>();
        while (resources.hasMoreElements()) {
            URL resource = resources.nextElement();
            dirs.add(new File(resource.getFile()));
        }
        ArrayList<Class<T>> classes = new ArrayList<Class<T>>();
        for (File directory : dirs) {
            classes.addAll(findPagesClasses(directory, packageName, basePageClass));
        }
        return classes;
    }

    /**
     * Recursive method used to find all classes in a given directory and subdirs.
     * 
     * @param directory The base directory
     * @param packageName The package name for classes found inside the base dirsectory
     * @param basePageClass classe base que deve ser retornada
     * @param <T> Tipo da classe que deve ser retornada
     * @return The classes
     * @throws ClassNotFoundException se acontecer algum erro
     */
    @SuppressWarnings("unchecked")
    private static <T> List<Class<T>> findPagesClasses(File directory, String packageName, Class<T> basePageClass)
            throws ClassNotFoundException {
        List<Class<T>> classes = new ArrayList<Class<T>>();
        if (!directory.exists()) {
            return classes;
        }
        File[] files = directory.listFiles();
        for (File file : files) {
            if (file.isDirectory()) {
                classes.addAll(findPagesClasses(file, packageName + "." + file.getName(), basePageClass));
            } else if (file.getName().endsWith(CLASS)) {
                Class<?> clazz = Class.forName(packageName + '.' + file.getName().substring(0, file.getName().length() - CLASS.length()));

                if (basePageClass.isAssignableFrom(clazz)) {
                    classes.add((Class<T>) clazz);
                }
            }
        }
        return classes;
    }
}
